import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import type { IStudent, IStudentCreateRequest, IStudentUpdateRequest, IStudentQueryParams } from '@/types/student/student';
import { StudentStatusEnum } from '@/types/student/enums';
import { studentService } from '@/services/student';
import type { IAsyncState, IFilterState } from '@/types/common/base';

/**
 * 学生状态接口
 * @description 定义学生状态管理的完整接口
 */
export interface IStudentState {
  // 数据状态
  /** 学生列表 */
  students: IStudent[];
  /** 当前选中的学生 */
  selectedStudent: IStudent | null;
  /** 选中的学生ID列表（用于批量操作） */
  selectedStudentIds: string[];
  
  // 异步状态
  /** 异步操作状态 */
  async: IAsyncState;
  
  // UI状态
  /** 是否显示学生表单 */
  showStudentForm: boolean;
  /** 表单模式 */
  formMode: 'create' | 'edit';
  /** 是否显示学生详情 */
  showStudentDetail: boolean;
  /** 是否显示批量操作面板 */
  showBatchPanel: boolean;
  
  // 筛选状态
  /** 筛选条件 */
  filters: IFilterState<{
    /** 年级筛选 */
    grade?: string;
    /** 班级筛选 */
    class?: string;
    /** 状态筛选 */
    status?: StudentStatusEnum;
    /** 性别筛选 */
    gender?: 'male' | 'female' | 'other';
  }>;
  
  // Actions - 数据操作
  /** 获取所有学生 */
  fetchStudents: (queryParams?: IStudentQueryParams) => Promise<void>;
  /** 添加学生 */
  addStudent: (studentData: IStudentCreateRequest) => Promise<void>;
  /** 更新学生 */
  updateStudent: (id: string, studentData: Omit<IStudentUpdateRequest, 'id'>) => Promise<void>;
  /** 删除学生 */
  deleteStudent: (id: string) => Promise<void>;
  /** 批量删除学生 */
  batchDeleteStudents: (ids: string[]) => Promise<void>;
  /** 搜索学生 */
  searchStudents: (keyword: string) => Promise<void>;
  
  // Actions - 选择操作
  /** 选择学生 */
  selectStudent: (student: IStudent | null) => void;
  /** 切换学生选择状态 */
  toggleStudentSelection: (studentId: string) => void;
  /** 选择所有学生 */
  selectAllStudents: () => void;
  /** 清空选择 */
  clearSelection: () => void;
  
  // Actions - UI操作
  /** 设置表单显示状态 */
  setShowStudentForm: (show: boolean) => void;
  /** 设置表单模式 */
  setFormMode: (mode: 'create' | 'edit') => void;
  /** 设置详情显示状态 */
  setShowStudentDetail: (show: boolean) => void;
  /** 设置批量操作面板显示状态 */
  setShowBatchPanel: (show: boolean) => void;
  
  // Actions - 筛选操作
  /** 更新筛选条件 */
  updateFilters: (filters: Partial<IStudentState['filters']['filters']>) => void;
  /** 设置搜索关键词 */
  setSearchKeyword: (keyword: string) => void;
  /** 设置排序 */
  setSorting: (sortBy: string, sortOrder: 'asc' | 'desc') => void;
  /** 重置筛选条件 */
  resetFilters: () => void;
  
  // Actions - 其他操作
  /** 重置状态 */
  reset: () => void;
  /** 刷新数据 */
  refresh: () => Promise<void>;
}

/**
 * 学生状态管理
 * @description 使用 Zustand 实现的学生状态管理
 */
export const useStudentStore = create<IStudentState>()(
  devtools(
    persist(
      immer((set, get) => ({
        // 初始状态
        students: [],
        selectedStudent: null,
        selectedStudentIds: [],
        async: {
          loading: false,
          error: null,
          lastUpdated: null
        },
        showStudentForm: false,
        formMode: 'create',
        showStudentDetail: false,
        showBatchPanel: false,
        filters: {
          filters: {},
          searchKeyword: '',
          sortBy: 'name',
          sortOrder: 'asc'
        },

        // Actions 实现 - 数据操作
        fetchStudents: async (queryParams?: IStudentQueryParams) => {
          set((state) => {
            state.async.loading = true;
            state.async.error = null;
          });

          try {
            const result = await studentService.getAllStudents(queryParams);
            if (result.success) {
              set((state) => {
                state.students = result.data;
                state.async.loading = false;
                state.async.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.async.loading = false;
                state.async.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.async.loading = false;
              state.async.error = error instanceof Error ? error.message : '获取学生列表失败';
            });
          }
        },

        addStudent: async (studentData: IStudentCreateRequest) => {
          set((state) => {
            state.async.loading = true;
            state.async.error = null;
          });

          try {
            const result = await studentService.createStudent(studentData);
            if (result.success) {
              set((state) => {
                state.students.push(result.data);
                state.async.loading = false;
                state.showStudentForm = false;
              });
            } else {
              set((state) => {
                state.async.loading = false;
                state.async.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.async.loading = false;
              state.async.error = error instanceof Error ? error.message : '添加学生失败';
            });
            throw error;
          }
        },

        updateStudent: async (id: string, studentData: Omit<IStudentUpdateRequest, 'id'>) => {
          set((state) => {
            state.async.loading = true;
            state.async.error = null;
          });

          try {
            const result = await studentService.updateStudent(id, studentData);
            if (result.success) {
              set((state) => {
                const index = state.students.findIndex(student => student.id === id);
                if (index !== -1) {
                  state.students[index] = result.data;
                }
                // 更新选中的学生
                if (state.selectedStudent?.id === id) {
                  state.selectedStudent = result.data;
                }
                state.async.loading = false;
                state.showStudentForm = false;
              });
            } else {
              set((state) => {
                state.async.loading = false;
                state.async.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.async.loading = false;
              state.async.error = error instanceof Error ? error.message : '更新学生信息失败';
            });
            throw error;
          }
        },

        deleteStudent: async (id: string) => {
          try {
            const result = await studentService.deleteStudent(id);
            if (result.success) {
              set((state) => {
                state.students = state.students.filter(student => student.id !== id);
                // 清除相关选择状态
                if (state.selectedStudent?.id === id) {
                  state.selectedStudent = null;
                }
                state.selectedStudentIds = state.selectedStudentIds.filter(selectedId => selectedId !== id);
              });
            } else {
              set((state) => {
                state.async.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.async.error = error instanceof Error ? error.message : '删除学生失败';
            });
            throw error;
          }
        },

        batchDeleteStudents: async (ids: string[]) => {
          set((state) => {
            state.async.loading = true;
            state.async.error = null;
          });

          try {
            const result = await studentService.batchDeleteStudents(ids);
            if (result.success) {
              set((state) => {
                state.students = state.students.filter(student => !ids.includes(student.id));
                // 清除相关选择状态
                if (state.selectedStudent && ids.includes(state.selectedStudent.id)) {
                  state.selectedStudent = null;
                }
                state.selectedStudentIds = state.selectedStudentIds.filter(selectedId => !ids.includes(selectedId));
                state.async.loading = false;
                state.showBatchPanel = false;
              });
            } else {
              set((state) => {
                state.async.loading = false;
                state.async.error = result.error || '批量删除失败';
              });
            }
          } catch (error) {
            set((state) => {
              state.async.loading = false;
              state.async.error = error instanceof Error ? error.message : '批量删除学生失败';
            });
            throw error;
          }
        },

        searchStudents: async (keyword: string) => {
          set((state) => {
            state.async.loading = true;
            state.async.error = null;
          });

          try {
            const result = await studentService.searchStudents(keyword);
            if (result.success) {
              set((state) => {
                state.students = result.data;
                state.async.loading = false;
                state.async.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.async.loading = false;
                state.async.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.async.loading = false;
              state.async.error = error instanceof Error ? error.message : '搜索学生失败';
            });
          }
        },

        // Actions 实现 - 选择操作
        selectStudent: (student: IStudent | null) => {
          set((state) => {
            state.selectedStudent = student;
          });
        },

        toggleStudentSelection: (studentId: string) => {
          set((state) => {
            const index = state.selectedStudentIds.indexOf(studentId);
            if (index > -1) {
              state.selectedStudentIds.splice(index, 1);
            } else {
              state.selectedStudentIds.push(studentId);
            }
          });
        },

        selectAllStudents: () => {
          set((state) => {
            state.selectedStudentIds = state.students.map(student => student.id);
          });
        },

        clearSelection: () => {
          set((state) => {
            state.selectedStudentIds = [];
            state.selectedStudent = null;
          });
        },

        // Actions 实现 - UI操作
        setShowStudentForm: (show: boolean) => {
          set((state) => {
            state.showStudentForm = show;
            if (!show) {
              state.selectedStudent = null;
            }
          });
        },

        setFormMode: (mode: 'create' | 'edit') => {
          set((state) => {
            state.formMode = mode;
          });
        },

        setShowStudentDetail: (show: boolean) => {
          set((state) => {
            state.showStudentDetail = show;
          });
        },

        setShowBatchPanel: (show: boolean) => {
          set((state) => {
            state.showBatchPanel = show;
          });
        },

        // Actions 实现 - 筛选操作
        updateFilters: (filters: Partial<IStudentState['filters']['filters']>) => {
          set((state) => {
            state.filters.filters = { ...state.filters.filters, ...filters };
          });
        },

        setSearchKeyword: (keyword: string) => {
          set((state) => {
            state.filters.searchKeyword = keyword;
          });
        },

        setSorting: (sortBy: string, sortOrder: 'asc' | 'desc') => {
          set((state) => {
            state.filters.sortBy = sortBy;
            state.filters.sortOrder = sortOrder;
          });
        },

        resetFilters: () => {
          set((state) => {
            state.filters = {
              filters: {},
              searchKeyword: '',
              sortBy: 'name',
              sortOrder: 'asc'
            };
          });
        },

        // Actions 实现 - 其他操作
        reset: () => {
          set((state) => {
            state.students = [];
            state.selectedStudent = null;
            state.selectedStudentIds = [];
            state.async = {
              loading: false,
              error: null,
              lastUpdated: null
            };
            state.showStudentForm = false;
            state.formMode = 'create';
            state.showStudentDetail = false;
            state.showBatchPanel = false;
            state.filters = {
              filters: {},
              searchKeyword: '',
              sortBy: 'name',
              sortOrder: 'asc'
            };
          });
        },

        refresh: async () => {
          const { fetchStudents } = get();
          await fetchStudents();
        }
      })),
      {
        name: 'student-store',
        partialize: (state) => ({
          students: state.students,
          filters: state.filters
        })
      }
    ),
    {
      name: 'student-store'
    }
  )
);